#include "linkList.h"
#include <stdio.h>
#include <stdlib.h>

//创建链表
LinkList_t * createLinkList() {
     LinkList_t *table=NULL;
     table = malloc(sizeof(LinkList_t));//为表头分配内存

     if (table == NULL) {
         fprintf(stderr, "Error allocating memory for SEQtable_t\n");
         return NULL;
     }

    table->head.next = NULL;
    table->head.val = 0;
    table->count=0;
    return table;
}

//释放链表
void releaseLinkList(LinkList_t *table) {
    if (table!= NULL) {
        node_t *p=&table->head;
        //站在-1号节点的位置，释放后面的节点
        while (p->next!= NULL) {
            node_t *temp=p->next;//保存要释放的节点
            p->next = temp->next;//指向要释放的节点的下一个节点
            free(temp); //释放要释放的节点
        }
        //释放头节点
        free(table);
    }
}

//头插
int insertLinkListHead(LinkList_t *table, Element_t value) {
    if (table == NULL) {
        printf( "Error: list is NULL\n");
        return -1;
    }

    node_t *p=&table->head;
    node_t *new_node=malloc(sizeof(node_t));
    if (new_node == NULL) { //新节点分配失败
        fprintf(stderr, "Error allocating memory for new_node\n");
        return -1;
    }

   new_node->val = value;
   new_node->next = p->next;
   p->next = new_node;

   table->count++;
   return 0;
}

//任意位置插入
int insertLinkListPos(LinkList_t *table, int pos, Element_t value) {
    if (table == NULL) {
        printf("Error: table is NULL\n");
        return -1;
    }
    //插入位置合理性检查
    if (pos < 0 || pos > table->count) {
       printf("pos is out of range\n");
        return -1;
    }

    node_t *p=&table->head;
    int index=-1;//头节点的位置是-1
    while (index<pos-1) {//找到插入位置的前一个节点
        p=p->next;
        index++;
    }

    node_t *new_node=malloc(sizeof(node_t));

    new_node->val = value;
    new_node->next = p->next;
    p->next = new_node;
    table->count++;
    return 0;
}

//删除值为value的节点
int deleteLinkListValue(LinkList_t *table, Element_t value) {
    if (table == NULL) {
        printf("Error: table is NULL\n");
        return -1;
    }

    //查找要删除的前一个节点
    node_t *p=&table->head;
    while (p->next != NULL) {
        if (p->next->val == value) break;
        p=p->next;
    }

    //没有找到要删除的节点
    if (p->next==NULL){printf("Not find %d\n", value);return 0;}

    node_t *temp=p->next;
    p->next = temp->next;
    free(temp);
    --table->count;

    return 0;
}


//打印链表
void showLinkList(const LinkList_t *table) {
    if (table == NULL) {
        printf( "Error: table is NULL\n");
        return;
    }

    node_t *p = table->head.next;
    printf("LinkList's size is %d\n", table->count);
    while (p != NULL) {
        printf("%d\t", p->val);
        p = p->next;
    }
    printf("\n");
}


